package com.zklh.leetcode.other.problem1;

/**
 * @ClassName LongestCommonPrefix
 * @Description
 * @Author 坐看落花
 * @Date 2019/7/12 20:20
 * @Version 1.0
 **/
public class LongestCommonPrefix {
    public String longestCommonPrefix(String strs[]) {
        int width = 1;
        int max = 1000;
        boolean flag = true;
        // 取到数组中所有字符串最短的长度
        for (int i = 0; i < strs.length; i++) {
            int len = strs[i].length();
            if(len < max){
                max = len;
            }
        }
        while(width <= max && flag){
            // 取到第一个字符串的前width位子字符串
            String s = strs[0].substring(0,width);
            for (int i = 1; i < strs.length; i++) {
                // 取字符串数组中剩下的每一位字符串的前width位字符
                String tmps = strs[i].substring(0,width);
                if(s.equals(tmps) ){
                    if(i == strs.length-1){
                        width ++;
                    }
                }else{
                    flag = false;
                    break;
                }

            }
        }
        String result = strs[0].substring(0,width-1);
        return result;
    }

    public static void main(String[] args){
        LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix();
        String[] strs = new String[3];
        strs[0] = "flower";
        strs[1] = "flow";
        strs[2] = "floight";
        System.out.println(longestCommonPrefix.longestCommonPrefix(strs));
    }

}
